import React, { useRef, useState } from 'react';
import { Button, message, Form, Input, Radio, Spin, Select } from 'antd';
import { DrawerForm } from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PlusOutlined, FormOutlined } from '@ant-design/icons';
import { add, edit, update } from '@/services/admin/auth/admin/api';
import { getGroupList, getProjectList } from '@/services/admin/common/api';
interface PorpsType {
  onConfirm: () => void;
  id?: number;
  disabled?: boolean;
}
const FormIndex: React.FC<PorpsType> = (porps) => {
  const restFormRef = useRef<ProFormInstance>();
  const [loading, setLoading] = useState<boolean>(porps.id ? false : true);
  const [groupList, setGroupList] = useState<API.GroupItem[]>([]);
  const [groupListLoading, setGroupListLoading] = useState<boolean>(false);
  const [projectList, setProjectList] = useState<API.ProjectItem[]>([]);
  const [projectListLoading, setProjectListLoading] = useState<boolean>(false);

  const formData: API.AdminAdminForm = {
    id: null,
    name: '',
    status: 1,
    group_id: null,
    project_id: [],
    username: '',
    password: '',
    password_confirmation: '',
    phone: '',
  };
  return (
    <DrawerForm<API.AdminAdminForm>
      layout="horizontal"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 20 }}
      formRef={restFormRef}
      initialValues={formData}
      title={porps.id ? '编辑' : '添加'}
      autoFocusFirstInput
      isKeyPressSubmit
      trigger={
        porps.id ? (
          <Button type="primary" disabled={porps.disabled ? true : false} size="small">
            <FormOutlined />
            编辑
          </Button>
        ) : (
          <Button type="primary">
            <PlusOutlined />
            添加
          </Button>
        )
      }
      drawerProps={{
        forceRender: true,
        destroyOnClose: true,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              loading={loading ? false : true}
              key="extra-reset"
              onClick={async () => {
                const id = props.form?.getFieldValue('id');
                if (id) {
                  await setLoading(false);
                  const res = await edit(id);
                  if (res.status === 20000) {
                    restFormRef.current?.setFieldsValue(res.data);
                    await setLoading(true);
                  }
                } else {
                  props.reset();
                }
              }}
            >
              重置
            </Button>,
          ];
        },
      }}
      onFinish={async (values: any) => {
        if (!Number.isInteger(values.ico_id)) {
          values.ico_id = values.ico_id && values.ico_id[0].id;
        }
        if (!Number.isInteger(values.logo_id)) {
          values.logo_id = values.logo_id && values.logo_id[0].id;
        }
        let res: any = {};
        if (porps.id) {
          res = await update(porps.id, values);
        } else {
          res = await add(values);
        }
        if (res.status === 20000) {
          message.success(res.message);
          porps.onConfirm();
          return true;
        }
        return false;
      }}
      onVisibleChange={async (visible) => {
        if (visible) {
          if (porps.id) {
            await setLoading(false);
            const res = await edit(porps.id);
            if (res.status === 20000) {
              await restFormRef.current?.setFieldsValue(res.data);
              await setLoading(true);
            }
          }
          await setGroupListLoading(true);
          const groupRes = await getGroupList();
          if (groupRes.status == 20000) {
            await setGroupListLoading(false);
            await setGroupList(groupRes.data);
          }
          await setProjectListLoading(true);
          const projectRes = await getProjectList();
          if (projectRes.status == 20000) {
            await setProjectListLoading(false);
            await setProjectList(projectRes.data);
          }
        }
      }}
    >
      <Spin spinning={loading ? false : true}>
        {loading && (
          <>
            <Form.Item
              label="所属角色"
              name="group_id"
              rules={[{ required: true, message: '请选择所属角色' }]}
            >
              <Select
                allowClear={true}
                showSearch={true}
                filterOption={(input, option: any) => {
                  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}
                loading={groupListLoading}
                notFoundContent="暂无可选角色"
                placeholder="请选择所属角色"
              >
                {groupList.map((item) => {
                  return (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              label="所属项目"
              name="project_id"
              rules={[{ required: true, message: '请选择所属项目' }]}
            >
              <Select
                allowClear={true}
                showSearch={true}
                mode="multiple"
                filterOption={(input, option: any) => {
                  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
                }}
                loading={projectListLoading}
                notFoundContent="暂无可选项目"
                placeholder="请选择所属项目"
              >
                {projectList.map((item) => {
                  return (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}({['内容管理', '企业官网'][item.type - 1]})
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名' }]}>
              <Input maxLength={30} allowClear placeholder="请输入姓名" />
            </Form.Item>

            <Form.Item
              label="手机号"
              name="phone"
              rules={[
                { required: true, message: '请输入手机号' },
                () => ({
                  validator(_, value) {
                    const re = /^1[34578]\d{9}$/;
                    if (re.test(value)) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('请输入正确的手机号'));
                  },
                }),
              ]}
            >
              <Input maxLength={11} allowClear placeholder="请输入手机号" />
            </Form.Item>
            <Form.Item
              label="账号"
              name="username"
              rules={[
                { required: true, message: '请输入账号' },
                () => ({
                  validator(_, value) {
                    const re = /^[a-zA-Z0-9]{4,14}$/;
                    if (re.test(value)) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('账号必须4到14位的数字或字母'));
                  },
                }),
              ]}
            >
              <Input maxLength={14} allowClear placeholder="请输入账号" />
            </Form.Item>
            {!porps.id && (
              <>
                <Form.Item
                  label="密码"
                  name="password"
                  rules={[
                    { required: true, message: '请输入密码' },
                    () => ({
                      validator(_, value) {
                        const re = /^[a-zA-Z0-9]{4,14}$/;
                        if (re.test(value)) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('密码必须4到14位的数字或字母'));
                      },
                    }),
                  ]}
                >
                  <Input.Password maxLength={14} allowClear placeholder="请输入密码" />
                </Form.Item>
                <Form.Item
                  label="确认密码"
                  name="password_confirmation"
                  rules={[
                    { required: true, message: '请输入确认密码' },
                    ({ getFieldValue }) => ({
                      validator(_, value) {
                        if (!value || getFieldValue('password') === value) {
                          return Promise.resolve();
                        }
                        return Promise.reject(new Error('密码和确认密码输入不一致'));
                      },
                    }),
                  ]}
                >
                  <Input.Password maxLength={14} allowClear placeholder="请输入确认密码" />
                </Form.Item>
              </>
            )}

            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Radio.Group name="status">
                <Radio value={0}>禁用</Radio>
                <Radio value={1}>启用</Radio>
              </Radio.Group>
            </Form.Item>
          </>
        )}
      </Spin>
    </DrawerForm>
  );
};
export default FormIndex;
